package first.endtoend

import net.sf.json.JSONObject
import org.springframework.dao.DataIntegrityViolationException

class NotificationController
{


    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def filterPaneService
    def sendNotificationService

    def index()
    {
        redirect(action: "list", params: params)
    }

    def list(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        [notificationInstanceList: Notification.list(params), notificationInstanceTotal: Notification.count()]
    }

    def create()
    {
        [notificationInstance: new Notification(params)]
    }

    def save()
    {
        def notificationInstance = new Notification(params)
        if (!notificationInstance.save(flush: true))
        {
            render(view: "create", model: [notificationInstance: notificationInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'notification.label', default: 'Notification'), notificationInstance.id])
        redirect(action: "show", id: notificationInstance.id)
    }

    def show(Long id)
    {
        def notificationInstance = Notification.get(id)
        if (!notificationInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'notification.label', default: 'Notification'), id])
            redirect(action: "list")
            return
        }

        [notificationInstance: notificationInstance]
    }

    def edit(Long id)
    {
        def notificationInstance = Notification.get(id)
        if (!notificationInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'notification.label', default: 'Notification'), id])
            redirect(action: "list")
            return
        }

        [notificationInstance: notificationInstance]
    }

    def update(Long id, Long version)
    {
        def notificationInstance = Notification.get(id)
        if (!notificationInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'notification.label', default: 'Notification'), id])
            redirect(action: "list")
            return
        }

        if (version != null)
        {
            if (notificationInstance.version > version)
            {
                notificationInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'notification.label', default: 'Notification')] as Object[],
                        "Another user has updated this Notification while you were editing")
                render(view: "edit", model: [notificationInstance: notificationInstance])
                return
            }
        }

        notificationInstance.properties = params

        if (!notificationInstance.save(flush: true))
        {
            render(view: "edit", model: [notificationInstance: notificationInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'notification.label', default: 'Notification'), notificationInstance.id])
        redirect(action: "show", id: notificationInstance.id)
    }

    def delete(Long id)
    {
        def notificationInstance = Notification.get(id)
        if (!notificationInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'notification.label', default: 'Notification'), id])
            redirect(action: "list")
            return
        }

        try
        {
            notificationInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'notification.label', default: 'Notification'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e)
        {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'notification.label', default: 'Notification'), id])
            redirect(action: "show", id: id)
        }
    }

    /*  def filter = {
          if(!params.max) params.max = 10
          render( view:'list',
                  model:[ notificationInstanceList: filterPaneService.filter( params, Notification ),
                          notificationInstanceTotal: filterPaneService.count( params, Notification ),
                          filterParams: org.grails.plugin.filterpane.FilterPaneUtils.extractFilterParams(params),
                          params:params ] )
      }
  */

    /*
  @author: Olfa
  this method send notification to agents related to adding a new Product or Family or Aid
   */

    def sendNotificationsToAll()
    {

        println("executing send Notifs")
        List<Long> listIdProduct = new ArrayList<Long>()
        List<Long> listIdFamily = new ArrayList<Long>()
        List<Long> listIdAid = new ArrayList<Long>()

        List<Notification> listNotif = Notification.findAll()
        println("***" + listNotif)
        List<Agent> listAgentToNotif = Agent.findAllByRegIdIsNotNull()

        NotificationView notification
        List<NotificationView> allNotifsToSend = new ArrayList<NotificationView>()
        listNotif.each {

            notification = new NotificationView()
            if (it.modelName.equals(Family.getSimpleName()))
            {
                listIdFamily.add(it.id)
                // listAgentToNotifFamily.add(it.agent)
                notification.code = it.code
                notification.data = listIdFamily
            } else if (it.modelName.equals(Product.getSimpleName()))
            {
                listIdProduct.add(it.id)
                // listAgentToNotifProduct.add(it.agent)
                notification.code = it.code
                notification.data = listIdProduct
            } else if (it.modelName.equals(Aid.getSimpleName()))
            {
                listIdAid.add(it.id)
                // listAgentToNotifAid.add(it.agent)
                notification.code = it.code
                notification.data = listIdAid
            }
            allNotifsToSend.add(notification)
        }

        JSONObject jsonNotif
        if (allNotifsToSend != null)
        {
            allNotifsToSend.each {
                jsonNotif = JsonHelper.createJsonObject(it)
                sendNotificationService.sendNotificationToAll(listAgentToNotif, jsonNotif.toString())
            }
        } else
        {
            println("no notifs to send!!!")
        }

        redirect(action: "list")


    }


    def sendNotification(Long id)
    {
        println("this is the id of notif to send " + id)

        def notificationInstance = Notification.get(id)
        NotificationView notification
        List<Long> listIdProduct = new ArrayList<Long>()
        List<Long> listIdFamily = new ArrayList<Long>()
        List<Long> listIdAid = new ArrayList<Long>()

        List<Agent> listAgentToNotif = Agent.findAllByRegIdIsNotNull()

        if (notificationInstance)
        {
            notification = new NotificationView()
            if (notificationInstance.modelName.equals(Family.getSimpleName()))
            {
                println("HERE idModel iis " + notificationInstance.idModel)
                listIdFamily.add(notificationInstance.idModel)
                // listAgentToNotifFamily.add(it.agent)
                notification.code = notificationInstance.code
                notification.data = listIdFamily
            } else if (notificationInstance.modelName.equals(Product.getSimpleName()))
            {
                listIdProduct.add(notificationInstance.idModel)
                // listAgentToNotifProduct.add(it.agent)
                notification.code = notificationInstance.code
                notification.data = listIdProduct
            } else if (notificationInstance.modelName.equals(Aid.getSimpleName()))
            {
                listIdAid.add(notificationInstance.idModel)
                // listAgentToNotifAid.add(it.agent)
                notification.code = notificationInstance.code
                notification.data = listIdAid
            }

            JSONObject jsonNotif

            jsonNotif = JsonHelper.createJsonObject(notification)
            println("***** here jSONNotif : " + jsonNotif)
            if (notificationInstance.agent)
            {      //here send notif to a specific agent
                sendNotificationService.sendNotification(notificationInstance.agent, jsonNotif.toString())

            } else
            {
                sendNotificationService.sendNotificationToAll(listAgentToNotif, jsonNotif.toString())

            }


        } else
        {
            // no notification selected
        }


        redirect(action: "list")

    }
}
